package com.xoa.service.dingdingManage;

import com.xoa.controller.login.loginController;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.dingdingManage.UserDDMapMapper;
import com.xoa.dao.users.UserFunctionMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dev.dingding.service.DingdingService;
import com.xoa.model.common.SysPara;
import com.xoa.model.department.Department;
import com.xoa.model.dingdingManage.*;
import com.xoa.model.users.Users;
import com.xoa.service.users.UsersService;
import com.xoa.service.users.impl.UsersServiceImpl;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.dingding.DingDingTool;
import com.xoa.util.dingding.DingDingUrl;
import net.sf.json.JSON;
import net.sf.json.JsonConfig;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 张雨 on 2018/1/30.
 * 钉钉企业号
 */
@Service
public class DingdingManageService {

    @Autowired
    SysParaMapper sysParaMapper;

    @Autowired
    DepartmentMapper departmentMapper;

    @Autowired
    UsersMapper usersMapper;

    @Autowired
    UserDDMapMapper userDDMapMapper;

    @Autowired
    DingdingService dingdingService;

    String accessToken;

    List<DingdingUpdateDept> dingdingUpdateDepts = new ArrayList<>();

    List<DingdingUpdateDept> dingdingUpdateDepts1 = new ArrayList<>();
    //部门层级
    Integer n = 0;

    //设置钉钉基础参数
    public BaseWrapper baseDingDingSetting(String oaUrl, String appKey, String appSecret,String corpId,String agentId) {
        BaseWrapper wrapper = new BaseWrapper();
        SysPara webSite = sysParaMapper.querySysPara("DINGDINGQY_OAURL");
        SysPara appKeyPara = sysParaMapper.querySysPara("DINGDINGQY_APPKEY");
        SysPara appSecretPara = sysParaMapper.querySysPara("DINGDINGQY_APPSECRET");
        SysPara copyIdPara = sysParaMapper.querySysPara("DINGDINGQY_CORPID");
        SysPara agentIdPara = sysParaMapper.querySysPara("DINGDINGQY_AGENTID");

        try {
            //有该字段则进行更新操作，无该字段则进行插入操作
            if (webSite != null) {
                if(oaUrl!=null){
                    webSite.setParaValue(oaUrl);
                    sysParaMapper.updateSysPara(webSite);
                }
            } else {
                webSite = new SysPara();
                webSite.setParaName("DINGDINGQY_OAURL");
                if(oaUrl==null){
                    oaUrl = "";
                }
                webSite.setParaValue(oaUrl);
                sysParaMapper.insertSysPara(webSite);
            }

            if (appKeyPara != null) {
                if(appKey!=null){
                    appKeyPara.setParaValue(appKey);
                    sysParaMapper.updateSysPara(appKeyPara);
                }
            } else {
                appKeyPara = new SysPara();
                appKeyPara.setParaName("DINGDINGQY_APPKEY");
                appKeyPara.setParaValue(appKey);
                sysParaMapper.insertSysPara(appKeyPara);
            }

            if (appSecretPara != null) {
                if(appSecret!=null){
                    appSecretPara.setParaValue(appSecret);
                    sysParaMapper.updateSysPara(appSecretPara);
                }
            } else {
                appSecretPara = new SysPara();
                appSecretPara.setParaName("DINGDINGQY_APPSECRET");
                appSecretPara.setParaValue(appSecret);
                sysParaMapper.insertSysPara(appSecretPara);
            }

            if (copyIdPara != null) {
                if(corpId!=null){
                    copyIdPara.setParaValue(corpId);
                    sysParaMapper.updateSysPara(copyIdPara);
                }
            } else {
                copyIdPara = new SysPara();
                copyIdPara.setParaName("DINGDINGQY_CORPID");
                copyIdPara.setParaValue(corpId);
                sysParaMapper.insertSysPara(copyIdPara);
            }

            if(agentIdPara!=null){
                if(agentId!=null){
                    agentIdPara.setParaValue(agentId);
                    sysParaMapper.updateSysPara(agentIdPara);
                }
            } else {
                agentIdPara = new SysPara();
                agentIdPara.setParaName("DINGDINGQY_AGENTID");
                agentIdPara.setParaValue(agentId);
                sysParaMapper.insertSysPara(agentIdPara);
            }

            wrapper.setMsg("保存成功！");
            wrapper.setFlag(true);
        } catch (Exception e) {
            e.printStackTrace();
            wrapper.setMsg(e.getMessage());
            wrapper.setFlag(false);
        }
        return wrapper;
    }

    //获取钉钉基础参数
    public BaseWrapper baseDingDingGet() {
        BaseWrapper wrapper = new BaseWrapper();
        List<String> item = new ArrayList<>();
        item.add("DINGDINGQY_OAURL");
        item.add("DINGDINGQY_APPKEY");
        item.add("DINGDINGQY_APPSECRET");
        item.add("DINGDINGQY_CORPID");
        item.add("DINGDINGQY_AGENTID");

        List<SysPara> sysParaList = sysParaMapper.getSysParaList(item);
        if(sysParaList != null) {
            wrapper.setMsg("查询成功！");
            wrapper.setFlag(true);
            wrapper.setData(sysParaList);

        } else {
            wrapper.setMsg("查询失败！");
        }
        return wrapper;
    }

    //钉钉连接测试
    public BaseWrapper dingdingConnect() {
        BaseWrapper wrapper = new BaseWrapper();
        String accessToken = dingdingService.getAccessToken();
        if(!StringUtils.checkNull(accessToken)){
            wrapper.setFlag(true);
            wrapper.setStatus(true);
            wrapper.setMsg("连接成功");
        }
        return wrapper;
    }

    //获取oa部门列表
    public BaseWrapper dingdingGetDeptList(Integer deptId) {
        BaseWrapper wrapper = new BaseWrapper();

        List<Department> dingdingDeptList = departmentMapper.getChDept(deptId);
        if(dingdingDeptList != null) {
            wrapper.setFlag(true);
            wrapper.setMsg("查询成功！");
            wrapper.setData(dingdingDeptList);
        } else {
            wrapper.setMsg("查询失败！");
        }
        return wrapper;
    }

    //获取部门用户列表
    public ToJson<Department> dingdingGetUserList(Integer deptId) {
        ToJson<Department> toJson = new ToJson<>();
        try {
            List<Department> deptList = departmentMapper.getChDept(deptId);
            List<Users> usersList = usersMapper.getUsersByDeptId(deptId);
            toJson.setObj(deptList);
            toJson.setObject(usersList);

            toJson.setMsg("OK");
            toJson.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    //钉钉组织结构同步
    public BaseWrapper dingdingDeptSynchro() throws JSONException {
        BaseWrapper wrapper = new BaseWrapper();
        List<DingdingUpdateDept> updateDept = new ArrayList<>();
        List<Long> deleteDept = new ArrayList<>();

        DingdingCreateDept dingdingCreateDept;
        DingdingUpdateDept dingdingUpdateDept;

        String updateResult = "ok";
        String deleteResult = "ok";

        List<Department> deptList = departmentMapper.getDatagrid();

        String dingdingResult = DingDingTool.dingdingRequestGet(DingDingUrl.DINGDING_DEPT_LIST, accessToken);
        if(!getErrmsg(dingdingResult).equals("ok")) {
            wrapper.setMsg(getErrmsg(dingdingResult));
            return wrapper;
        }
        JSONObject jsonObject = new JSONObject(dingdingResult);
        JSONArray jsonArray = jsonObject.getJSONArray("department");

        //创建或更新部门
        for(Department department: deptList) {
            boolean create = true;
            boolean update = true;
            dingdingCreateDept = new DingdingCreateDept();
            dingdingUpdateDept = new DingdingUpdateDept();
            Integer parentid = departmentMapper.getParentDingdingId(department.getDeptId());
            //循环判断部门是否已加入钉钉组织架构
            for(int i = 1; i < jsonArray.length(); i ++) {
                if(jsonArray.getJSONObject(i).getString("id").equals(department.getDingdingDeptId())) {
                    //id存在则已加入钉钉，无需进行创建操作
                    create = false;
                    if((parentid == null||jsonArray.getJSONObject(i).getInt("parentid") == parentid)
                            &&jsonArray.getJSONObject(i).getString("name").equals(department.getDeptName())) {
                        //父部门id相同且名字相同则说明信息无变更，无需进行创建操作
                        update = false;
                        break;
                    }
                } else if(jsonArray.getJSONObject(i).getString("name").equals(department.getDeptName())) {
                    department.setDingdingDeptId(jsonArray.getJSONObject(i).getString("id"));
                    departmentMapper.editDept(department);
                    create = false;
                }
            }

            if(create) {
                //创建操作
                dingdingCreateDept.setName(department.getDeptName());
                if(department.getDeptParent()==0) {
                    //父部门id为0说明是根部门，设置钉钉父部门id为1
                    dingdingCreateDept.setParentid(1 + "");
                } else {
                    //设置父部门的钉钉id到钉钉创建类
                    dingdingCreateDept.setParentid(parentid + "");
                }
                //bean转换为JSONObject
                net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(dingdingCreateDept);
                String postData = jsonObj.toString();
                //创建部门，获取返回的id
                String result = DingDingTool.dingdingRequestPost(DingDingUrl.DINGDING_CREATE_DEPT, accessToken, postData);
                if(!getErrmsg(result).equals("ok")) {
                    wrapper.setMsg(getErrmsg(result));
                    return wrapper;
                }
                JSONObject resultJSON = new JSONObject(result);
                String dingdingDeptId = resultJSON.getString("id");
                //写入钉钉部门id
                department.setDingdingDeptId(dingdingDeptId);
                departmentMapper.editDept(department);
            } else if(update) {
                //更新操作
                dingdingUpdateDept.setName(department.getDeptName());
                dingdingUpdateDept.setId(Long.parseLong(department.getDingdingDeptId()));
                dingdingUpdateDept.setParentid(parentid + "");
                updateDept.add(dingdingUpdateDept);
            }
        }

        //钉钉那边有，本地没有则删除该部门
        for(int i = 1; i < jsonArray.length(); i ++) {
            boolean delete = true;
            for(Department department: deptList) {
                if(jsonArray.getJSONObject(i).getString("id").equals(department.getDingdingDeptId())) {
                    delete = false;
                    break;
                }
            }
            if(delete) {
                deleteDept.add(jsonArray.getJSONObject(i).getLong("id"));
            }
        }

        //发送更新部门请求
        for(DingdingUpdateDept sendUpdateDept: updateDept) {
            //bean转换为JSONObject
            net.sf.json.JSONObject jsonObj = net.sf.json.JSONObject.fromObject(sendUpdateDept);
            String postData = jsonObj.toString();
            String result = DingDingTool.dingdingRequestPost(DingDingUrl.DINGDING_UPDATE_DEPT, accessToken, postData);
            updateResult = getErrmsg(result);
            if(!updateResult.equals("ok")) {
                break;
            }
        }

        //发送删除部门请求
        for(Long id: deleteDept) {
            String deleteRequest = accessToken + "&id=" + id;
            String result = DingDingTool.dingdingRequestGet(DingDingUrl.DINGDING_DELETE_DEPT, deleteRequest);
            deleteResult = getErrmsg(result);
            if(!deleteResult.equals("ok")) {
                break;
            }
        }

        if(updateResult.equals("ok")&&deleteResult.equals("ok")) {
            wrapper.setFlag(true);
            wrapper.setMsg("同步成功！");
        } else {
            wrapper.setMsg("更新操作结果：" + updateResult + "！<br>删除操作结果：" + deleteResult + "！");
        }
        return wrapper;
    }

    //钉钉用户管理同步
    public BaseWrapper dingdingUserSynchro(String synchroUsers) throws JSONException {
        BaseWrapper wrapper = new BaseWrapper();
        DingdingUser dingdingUser;
        List<Integer> dingdingDeptList;
        String createResult = "ok";
        String updateResult = "ok";
        Integer successNum = 0;
        Integer failedNum = 0;
        String failedReason = "";

        String dingUrl;
        String dingRequest;
        synchroUsers = dealUserSynchroStr(synchroUsers);

        //第一次按部门分开
        for(String deptUsers: synchroUsers.split(";")) {

            //第二次将部门和人员分开
            String dept = deptUsers.split(":")[0];
            String users = deptUsers.split(":")[1];

            Integer dingdingDeptId = departmentMapper.getDingdingIdByDeptId(Integer.parseInt(dept));

            if(dingdingDeptId==0) {
                wrapper.setMsg("选中人员所在部门未同步到钉钉，请先同步组织结构！");
                return wrapper;
            }

            dingRequest = accessToken + "&department_id=" + dingdingDeptId;
            dingUrl = DingDingUrl.DINGDING_USER_LIST;
            //查询钉钉中该部门下的所有人员
            String dingdingResponse = DingDingTool.dingdingRequestGet(dingUrl, dingRequest);
            if(!getErrmsg(dingdingResponse).equals("ok")) {
                wrapper.setMsg(getErrmsg(dingdingResponse));
                return wrapper;
            }

            JSONObject jsonObject = new JSONObject(dingdingResponse);
            JSONArray jsonArray = jsonObject.getJSONArray("userlist");

            //第三次将人员分开
            for(String user: users.split(",")) {
                Users theUser = usersMapper.getUserByUid(Integer.parseInt(user));
                dingdingUser = new DingdingUser();
                dingdingDeptList = new ArrayList<>();
                String result = "";
                UserDDMap userDDMap = new UserDDMap();
                userDDMap.setOaUid(theUser.getUid() + "");

                //创建更新人员
                dingdingDeptList.add(dingdingDeptId);
                dingdingUser.setUserid(theUser.getByname());
                dingdingUser.setDepartment(dingdingDeptList);
                dingdingUser.setEmail(theUser.getEmail());
                dingdingUser.setMobile(theUser.getMobilNo());
                dingdingUser.setName(theUser.getUserName());
                dingdingUser.setPosition(theUser.getPost());
                net.sf.json.JSONObject sendJSONObject = net.sf.json.JSONObject.fromObject(dingdingUser);
                String sendMsg = sendJSONObject.toString();

                if(dingdingUser.getName()==null||"".equals(dingdingUser.getName())
                        ||dingdingUser.getMobile()==null||"".equals(dingdingUser.getMobile())) {
                    failedNum ++;
                    if(!failedReason.contains("、人员未设置电话号码")){
                        failedReason += "、人员未设置电话号码";
                    }
                    continue;
                }

                if(jsonArray.length() > 0) {
                    for(int i = 0; i < jsonArray.length(); i ++) {
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                        //userId相同，说明存在
                        if(theUser.getUserId().equals(jsonObject1.getString("userid"))) {
                            //如果有一个信息不相同，则更新。
                            if(!jsonObject1.getString("name").equals(theUser.getUserName())||
                                    !jsonObject1.getString("mobile").equals(theUser.getMobilNo())||
                                    !jsonObject1.getString("position").equals(theUser.getPost())||
                                    !jsonObject1.getString("email").equals(theUser.getEmail())||
                                    dingdingDeptId!=jsonObject1.getJSONArray("department").getInt(0)){

                                dingUrl = DingDingUrl.DINGDING_UPDATE_USER;
                                result = DingDingTool.dingdingRequestPost(dingUrl, accessToken, sendMsg);
                                updateResult = getErrmsg(result);
                            }
                            userDDMap.setDdUid(dingdingUser.getUserid());
                        } else {
                            dingUrl = DingDingUrl.DINGDING_CREATE_USER;
                            result = DingDingTool.dingdingRequestPost(dingUrl, accessToken, sendMsg);
                            createResult = getErrmsg(result);
                            JSONObject jsonObject2 = new JSONObject(result);
                            userDDMap.setDdUid(jsonObject2.getString("userid"));
                        }
                    }
                } else {
                    dingUrl = DingDingUrl.DINGDING_CREATE_USER;
                    result = DingDingTool.dingdingRequestPost(dingUrl, accessToken, sendMsg);
                    createResult = getErrmsg(result);
                    JSONObject jsonObject2 = new JSONObject(result);
                    userDDMap.setDdUid(jsonObject2.getString("userid"));
                }
                if(!createResult.equals("ok")||!updateResult.equals("ok")) {
                    failedNum ++;
                    if(!failedReason.contains("、" + getErrmsg(result))) {
                        failedReason += "、" + getErrmsg(result);
                    }
                } else {
                    successNum ++;
                    if(userDDMapMapper.getBindBoolean(theUser.getUid()) == 0) {
                        userDDMapMapper.insert(userDDMap);
                    }
                }
            }
        }

        if(failedReason.contains("、")) {
            failedReason = failedReason.replaceFirst("、", "");
            failedReason += "。";
        }
        String result = "成功：" + successNum + "个，失败：" + failedNum + "个";
        if(failedNum > 0) {
            result += "，失败原因：" + failedReason;
        }
        wrapper.setMsg(result);
        wrapper.setFlag(true);
        return wrapper;
    }

    //获取钉钉人员列表
    public BaseWrapper getDingdingUserList() throws JSONException {
        BaseWrapper wrapper = new BaseWrapper();
        List<DingdingBindUser> dingdingBindUserList = new ArrayList<>();

        //查出所有部门
        String dingUrl = DingDingUrl.DINGDING_DEPT_LIST;
        String dingdingDepts = DingDingTool.dingdingRequestGet(dingUrl, accessToken);
        if(!getErrmsg(dingdingDepts).equals("ok")) {
            wrapper.setMsg(getErrmsg(dingdingDepts));
            return wrapper;
        }
        JSONObject jsonObject = new JSONObject(dingdingDepts);
        JSONArray jsonArray = jsonObject.getJSONArray("department");

        for(int i = 0; i < jsonArray.length(); i ++) {
            Integer deptId = jsonArray.getJSONObject(i).getInt("id");

            //根据部门查出所有人员
            dingUrl = DingDingUrl.DINGDING_USER_SIMPLE_LIST;
            String dingRequest = accessToken + "&department_id=" + deptId;
            JSONObject theDeptsUsers = new JSONObject(DingDingTool.dingdingRequestGet(dingUrl, dingRequest));

            if(!theDeptsUsers.getString("errmsg").equals("ok")) {
                wrapper.setMsg(theDeptsUsers.getString("errmsg"));
                return wrapper;
            }
            JSONArray userList = theDeptsUsers.getJSONArray("userlist");

            if(userList.length() > 0) {
                for(int j = 0; j < userList.length(); j ++) {
                    JSONObject jsonObject1 = userList.getJSONObject(j);
                    DingdingBindUser dingdingBindUser = new DingdingBindUser();
                    dingdingBindUser.setName(jsonObject1.getString("name"));
                    dingdingBindUser.setUserid(jsonObject1.getString("userid"));
                    //查询绑定状态
                    UserDDMap userDDMap = userDDMapMapper.getUserDDMapByUserId(dingdingBindUser.getUserid());
                    if(userDDMap != null) {
                        dingdingBindUser.setBind(true);
                    }
                    dingdingBindUserList.add(dingdingBindUser);
                }
            }
        }
        wrapper.setFlag(true);
        wrapper.setMsg("查询成功");
        wrapper.setData(dingdingBindUserList);
        return wrapper;
    }

    //钉钉账号与OA账号绑定与解除绑定，type为0：绑定，type为1：解除绑定
    @Transactional(rollbackFor = RuntimeException.class)
    public BaseWrapper bindDingdingAndOA(String dingdingId, String uid, Integer type) {
        BaseWrapper wrapper = new BaseWrapper();
        UserDDMap userDDMap = new UserDDMap();
        UserDDMapExample example = new UserDDMapExample();
        Integer result;
        try {
            if(type == 0) {
                Integer uuid = Integer.parseInt(uid.split(",")[0]);
                Users users = usersMapper.getUsersByUid(uuid);
                if(users.getMobilNo()==null||"".equals(users.getMobilNo())) {
                    wrapper.setMsg("选中人员无电话号码，无法绑定！");
                    return wrapper;
                }else {
                    if (userDDMapMapper.getBindBoolean(uuid) == 0) {
                        userDDMap.setDdUid(dingdingId);
                        userDDMap.setOaUid(uuid + "");
                        result = userDDMapMapper.insertSelective(userDDMap);
                    } else {
                        wrapper.setMsg("该人员已绑定其他钉钉账号，请重新选择！");
                        return wrapper;
                    }
                }
            } else {
                example.or().andDdUidEqualTo(dingdingId);
                result = userDDMapMapper.deleteByExample(example);
            }

            if(result > 0) {
                wrapper.setFlag(true);
                wrapper.setMsg("操作成功！");
            } else {
                wrapper.setMsg("操作失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            wrapper.setMsg(e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        return wrapper;
    }

    //获取钉钉应用
    public BaseWrapper getDingdingApp(String appName) {
        BaseWrapper wrapper = new BaseWrapper();
        String appUrl = "";
        SysPara sysPara = sysParaMapper.querySysPara(appName);
        DingdingApp dingdingApp = new DingdingApp();

        switch (appName){
            case "DINGDINGQY_APP_XOA": appUrl = DingDingUrl.DINGDINGQY_APP_XOA;
                break;
        }
        dingdingApp.setDingdingAppId(sysPara.getParaValue());
        dingdingApp.setDingdingAppUrl(appUrl);

        if(dingdingApp != null) {
            wrapper.setFlag(true);
            wrapper.setMsg("查询成功！");
            wrapper.setData(dingdingApp);
        } else {
            wrapper.setMsg("查询失败！");
        }
        return wrapper;
    }

    //钉钉应用设置
    @Transactional(rollbackFor = RuntimeException.class)
    public BaseWrapper dingdingAppSetting(String appName, String appId) {
        BaseWrapper wrapper = new BaseWrapper();

        SysPara sysPara = new SysPara();
        sysPara.setParaName(appName);
        sysPara.setParaValue(appId);
        try {
            sysParaMapper.updateSysPara(sysPara);
            wrapper.setFlag(true);
            wrapper.setMsg("保存成功！");
        } catch (Exception e) {
            e.printStackTrace();
            wrapper.setMsg(e.getMessage());
            throw new RuntimeException("保存出错！");
        }
        return wrapper;
    }

    //钉钉组织架构管理获取部门列表
    public void dingdingDepSettingGet(HttpServletResponse response, Integer deptId) {
        String dingRequest = accessToken + "&fetch_child=false" + "&id=" + deptId;
        String result = DingDingTool.dingdingRequestGet(DingDingUrl.DINGDING_DEPT_LIST, dingRequest);
        try {
            ServletOutputStream out = response.getOutputStream();
            OutputStreamWriter ow = new OutputStreamWriter(out, "utf-8");
            ow.getEncoding();
            ow.write(result);
            ow.flush();
            ow.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //钉钉组织架构管理获取编辑页面下拉菜单
    public BaseWrapper dingdingDepSettingMenu() {
        BaseWrapper wrapper = new BaseWrapper();
        dingdingUpdateDepts = new ArrayList<>();
        dingdingUpdateDepts1 = new ArrayList<>();

        String result = DingDingTool.dingdingRequestGet(DingDingUrl.DINGDING_DEPT_LIST, accessToken);
        try {
            if(!getErrmsg(result).equals("ok")) {
                wrapper.setMsg(getErrmsg(result));
                return wrapper;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
        net.sf.json.JSONArray jsonArray = jsonObject.getJSONArray("department");

        DingdingUpdateDept dingdingUpdateDept = (DingdingUpdateDept) net.sf.json.JSONObject.toBean(jsonArray.getJSONObject(0), DingdingUpdateDept.class);
        dingdingUpdateDept.setParentid(0 + "");
        dingdingUpdateDepts1.add(dingdingUpdateDept);
        getMenu(1);

        if(dingdingUpdateDepts1.size() != 0) {
            wrapper.setFlag(true);
            wrapper.setMsg("获取成功！");
            wrapper.setData(dingdingUpdateDepts1);
        }
        return wrapper;
    }

    //钉钉组织架构管理编辑部门
    public BaseWrapper dingdingDepSettingEdit(DingdingUpdateDept dingdingUpdateDept) {
        BaseWrapper wrapper = new BaseWrapper();
        net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(dingdingUpdateDept);
        String postData = jsonObject.toString();
        String result = DingDingTool.dingdingRequestPost(DingDingUrl.DINGDING_UPDATE_DEPT, accessToken, postData);
        try {
            if(getErrmsg(result).equals("ok")) {
                wrapper.setFlag(true);
                wrapper.setMsg("更新成功！");
            } else {
                wrapper.setMsg(getErrmsg(result));
            }
        } catch (JSONException e) {
            e.printStackTrace();
            wrapper.setMsg(e.getMessage());
        }
        return wrapper;
    }

    //钉钉组织架构管理删除部门
    public BaseWrapper dingdingDepSettingDelete(Integer deptId) {
        BaseWrapper wrapper = new BaseWrapper();
        String dingRequest = accessToken + "&id=" + deptId;
        String result = DingDingTool.dingdingRequestGet(DingDingUrl.DINGDING_DELETE_DEPT, dingRequest);
        try {
            if(getErrmsg(result).equals("ok")) {
                wrapper.setFlag(true);
                wrapper.setMsg("删除成功！");
            } else {
                wrapper.setMsg(getErrmsg(result));
            }
        } catch (JSONException e) {
            e.printStackTrace();
            wrapper.setMsg(e.getMessage());
        }
        return wrapper;
    }


    //钉钉工具方法

    //获取钉钉接口的返回消息
    public String getErrmsg(String result) throws JSONException {
        JSONObject jsonObject = new JSONObject(result);
        return jsonObject.getString("errmsg");
    }

    //用户管理同步前端数据处理
    public String dealUserSynchroStr(String synchroUsers) {
        String result = ",";
        Integer deptId = 0;

        for(String one: synchroUsers.split(";")) {
            Integer nowDeptId = Integer.parseInt(one.split(",")[0]);
            String uid = one.split(",")[1];

            if (deptId == nowDeptId) {
                result += uid + ",";
            } else {
                result = result.substring(0, result.length() - 1);
                result += ";" + nowDeptId + ":" + uid + ",";
                deptId = nowDeptId;
            }
        }
        result = result.replaceFirst(";", "");
        result = result.substring(0, result.length() - 1);
        return result;
    }

    //递归获取下拉菜单
    public void getMenu(long id) {
        String dingRequest = accessToken + "&fetch_child=false" + "&id=" + id;
        String result = DingDingTool.dingdingRequestGet(DingDingUrl.DINGDING_DEPT_LIST, dingRequest);
        n ++;
        try {
            if(getErrmsg(result).equals("ok")) {
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                net.sf.json.JSONArray jsonArray = jsonObject.getJSONArray("department");
                if(!jsonArray.isEmpty()) {
                    dingdingUpdateDepts = jsonArray.toList(jsonArray, new DingdingUpdateDept(), new JsonConfig());
                    for(DingdingUpdateDept dingdingUpdateDept: dingdingUpdateDepts) {
                        dingdingUpdateDept.setParentid(n+"");
                        dingdingUpdateDepts1.add(dingdingUpdateDept);
                        getMenu(dingdingUpdateDept.getId());
                    }
                }
            }
            n --;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}